package ar.edu.unlu.sistemas.p2p.android;

import java.io.File;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RatingBar;
import android.widget.TextView;
import ar.edu.unlu.sistemas.p2p.business.util.QueryResultComparator;
import ar.edu.unlu.sistemas.p2p.business.vo.PingResultVO;
import ar.edu.unlu.sistemas.p2p.business.vo.QueryResultVO;

public class QueryActivity extends AbsP2PActivity implements OnClickListener {

	private Thread updateStateBarThread = new Thread() {
		
		public void run() {
			while (!isFinishing()) {
				try {
					//Se actualizan los imageButton
					mHandler.sendMessage(mHandler.obtainMessage(0));
					//Se realiza ping para mostrar info de la red P2P solo si el boton red fue presionado
					if (netStateUpdateLaunched) {
						String msgId = appService.ping();
						while (!appService.isTaskFinished(msgId)) {
							Thread.sleep(1000);
						}
						Iterator<PingResultVO> it = appService.finishPingResults(msgId).iterator();
						PingResultVO pingRVo;
						int ac = 0;
						int i = 0;
						while (it.hasNext()) {
							pingRVo = it.next();
							ac += pingRVo.getnFiles();
							i++;
						}
						Message msg = mHandler.obtainMessage(1);
						Bundle bundle = new Bundle();
						bundle.putString("text", "   Pares: "+String.valueOf(i)+" Documentos: "+String.valueOf(ac)+"   ");
						msg.setData(bundle);
						mHandler.sendMessage(msg);
						netStateUpdateLaunched = false;
					}
					Thread.sleep(5000);
		        } catch (InterruptedException ie) {
		        	
		        }
				
			}
		}
	};
	
	public final Handler mHandler = new Handler() {
		//Se envían mensajes al handler que realizarán una acción
		//determinada por este método debido a que otro thread que no
		//sea el creador de la UI puede modificarla
		//Este código se ejecuta en el main thread
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch(msg.what) {
				case 0:
					updateImageButton();
					break;	
				case 1:
					showNetWorkState(msg.getData().getString("text"));
					break;
				default:
					break;
			}
		}
	};
	
	private boolean netStateUpdateLaunched = false;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.query);
        Button btn = (Button)findViewById(R.id.button_query);
        btn.setOnClickListener(this);
        ImageButton ibtn = (ImageButton)findViewById(R.id.img_btn_index_sync);
        ibtn.setOnClickListener(this);
        ibtn = (ImageButton)findViewById(R.id.img_btn_connected);
        ibtn.setOnClickListener(this);
        bindService(new Intent(QueryActivity.this,AppService.class), mConnection, BIND_AUTO_CREATE);
    }
    
    public void onServiceConnectedWithActivity() {
    	super.onServiceConnectedWithActivity();
    	updateStateBarThread.start();
    }
    
    public void onClick(View v) {
    	switch (v.getId()) {
    	case R.id.button_query:
    		EditText edt = (EditText) this.findViewById(R.id.edit_text_query);
			String query = edt.getText().toString();
			this.doingQuery(query);
			edt.setText(null);
    		break;
    	case R.id.img_btn_index_sync:
    		ImageButton btn = (ImageButton) this.findViewById(R.id.img_btn_index_sync);
    		btn.setEnabled(false);
    		this.appService.updateIndexAsinc();
    		break;
    	case R.id.img_btn_connected:
    		if(this.appService.isConnected()) {
    			netStateUpdateLaunched = true;
    		} else {
    			this.appService.connect();
    		}
    		break;
    	default:
    		if ((v.getId() >= 1000) && (v.getId() <= 2000)) {
    			DocumentLinearLayout dll = (DocumentLinearLayout) v;
    			File f = appService.getFile(dll.getDocumentVO().getPath());
    			if (f!=null) {
    				Intent intent = new Intent();
        			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        			intent.setAction(android.content.Intent.ACTION_VIEW);
        			String type = appService.getMIMEType(f);
        			intent.setDataAndType(Uri.fromFile(f), type);
        			startActivity(intent);
    			} 
    		}
    		break;
    	}
    }
    
    private void updateImageButton() {
    	ImageButton ibtn = (ImageButton) findViewById(R.id.img_btn_connected);
    	if (appService.isConnected()) {
        	ibtn.setImageResource(R.drawable.online);
    	} else {
        	ibtn.setImageResource(R.drawable.offline);
    	}
        ibtn = (ImageButton) findViewById(R.id.img_btn_index_sync);
        
        if (!appService.isIndexUpdateLaunched()) {
        	if (appService.isIndexUpdated()) {
            	ibtn.setImageResource(R.drawable.online);
            	ibtn.setEnabled(false);
            } else {
            	ibtn.setImageResource(R.drawable.offline);
              	ibtn.setEnabled(true);
            	
            }
        }
        
    }
    
    private void showNetWorkState(String text) {
    	TextView tv = (TextView) this.findViewById(R.id.txt_net_state);
    	tv.setTextSize(10);
    	tv.setText(text);
    }
    
    private void doingQuery(String query) {
    	boolean flag = true;
    	QueryResultVO vo;
    	Collection<QueryResultVO> queryResults;
    	Iterator<QueryResultVO> it;
    	LinearLayout ll = (LinearLayout) this.findViewById(R.id.layout_query_docs_result);
    	ll.removeAllViews();
    	String msgId = this.appService.doQuery(query);
    	while (flag) {
    		ll.removeAllViews();
    		if(!this.appService.isTaskFinished(msgId)) {
    			queryResults = this.appService.getQueryResults(msgId);
    		} else {
    			flag = false;
    			queryResults = this.appService.finishQueryResults(msgId);
    		}
    		Collections.sort((List<QueryResultVO>)queryResults, new QueryResultComparator());
    		it = queryResults.iterator();
    		TextView tv;
    		LinearLayout lldoc;
    		LinearLayout lltxt;
    		LinearLayout llrat;
    		RatingBar rating;
    		LayoutParams llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
    		llp.setMargins(0, 1, 0, 1);
    		LayoutParams llp2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
    		int docId = 1000;
    		while (it.hasNext()) {
    			vo = it.next();
    			
    			lldoc = new DocumentLinearLayout(this,vo);
    			lldoc.setId(docId++);
    			lldoc.setLayoutParams(llp);
    			lldoc.setBackgroundResource(R.drawable.border);
    			lldoc.setClickable(true);
    			lldoc.setOnClickListener(this);
    			
    			lltxt = new LinearLayout(this);
    			lltxt.setGravity(Gravity.LEFT);
    			tv = new TextView(this);
    			tv.setTextSize(22);
    			tv.setText(vo.getDocName());
    			lltxt.addView(tv);
    			lldoc.addView(lltxt);
    			
    			llrat = new LinearLayout(this);
    			llrat.setLayoutParams(llp2);
    			llrat.setGravity(Gravity.RIGHT);
    			rating = new RatingBar(this,null,android.R.attr.ratingBarStyleSmall);
    			rating.setRating(vo.getValue()*5);
    			llrat.addView(rating);
    			lldoc.addView(llrat);
    			
    			ll.addView(lldoc);
    		}
    	}
    }
    
  //Crea el menu
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }
    
    //Maneja la selección de un item en el menú
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
    	case R.id.menu_item_preferences:
    		startActivity(new Intent(QueryActivity.this,PreferencesActivity.class));
            return true;
        case R.id.menu_item_p2p_functions:
        	startActivity(new Intent(QueryActivity.this,SomeActionActivity.class));
            return true;
        case R.id.menu_item_index:
        	startActivity(new Intent(QueryActivity.this,IndexActivity.class));
        	return true;
        case R.id.menu_item_quit:
        	//Ítem del menu SALIR, sale de la app
        	Log.i("Main Menu","Eligio Opcion SALIR");
        	this.appService.stopForeground(true);
        	this.stopService(new Intent(QueryActivity.this,AppService.class)); 
        	this.unbindService(this.mConnection);
        	this.finish();
            return true;
        }
        return false;
    }
    
    public void onBackPressed() {
    }

}
